package com.wmh.baseservice.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.limiter.RequestLimiter;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.shiro.jwt.JwtTokenUtil;
import com.wmh.baseservice.common.utils.*;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.skd.service.SkdLeaderInfoService;
import com.wmh.baseservice.skd.service.SkdMemberInfoService;
import com.wmh.baseservice.system.pojo.SysLocation;
import com.wmh.baseservice.system.service.SysLocationService;
import com.wmh.baseservice.user.enums.GroupGoodsOrderStatusEnum;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsEvaluate;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.vo.FreightTemplate;
import com.wmh.baseservice.user.pojo.vo.UsGroupGoodsOrderRespVO;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsEvaluateService;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wmh generator
 * @since 2022-03-07
 */
@Api(tags = "用户端-团购订单相关接口")
@RestController
@RequestMapping(value = "user/usGroupGoodsOrder", produces = "text/plain;charset=utf-8")
@Slf4j
public class UsGroupGoodsOrderController {

    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private MerchantGroupGoodsPriceService merchantGroupGoodsPriceService;
    @Resource
    private SkdGoodsSpecService merchantSpecService;
    @Resource
    private UsAddressService usAddressService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantFreightTemplateService merchantFreightTemplateService;
    @Resource
    private SysLocationService sysLocationService;
    @Resource
    private UsEvaluateService usEvaluateService;
    @Resource
    private SkdLeaderInfoService skdLeaderInfoService;
    @Resource
    private SkdMemberInfoService skdMemberInfoService;

//    @ApiOperation("团购商品详情")
//    @PostMapping("groupGoods/detail")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "团购商品id", required = false),
//    })
//    @ParameterVerify(notNull = "id")
//    public String detail(Long id) {
//        // where 条件映射
//        Map<String, Object> map = new HashMap<>();
//        JSONObject object = new JSONObject(true);
//        //商品信息
//        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
//        object.put("merchantGroupGoods", merchantGroupGoods);
//        //规格列表
//
//        List<SkdGoodsSpec> merchantSpecs = null;
//        // 指定当前商品批次
//        map.put("batch", merchantGroupGoods.getBatchNum());
//        // 是否有规格
//        if (merchantGroupGoods.getHasSpec() == 1) {
//            // 得到当前团购商品的规格列表
//            merchantSpecs = merchantSpecService.listForUpdate(new QueryWrapper<SkdGoodsSpec>().eq(SkdGoodsSpec.TYPE, 2).eq(SkdGoodsSpec.GOODS_ID, merchantGroupGoods.getId()));
//            merchantSpecs.forEach(item -> {
//                map.put("specId", item.getId());
//                // 得到当前团购当前规格已下单的数量
//                int totalCount = usGroupGoodsOrderService.totalCount(map);
//
//                // 得到当前规格的具体优惠挡位列表 升序排序
//                List<MerchantGroupGoodsPrice> priceList = merchantGroupGoodsPriceService.list(new QueryWrapper<MerchantGroupGoodsPrice>()
//                        .eq(MerchantGroupGoodsPrice.SPEC_ID, item.getId())
//                        .orderByAsc(MerchantGroupGoodsPrice.SUCCESS_GEAR));
//
//                // 如果没查到 将该规格未达成优惠的购买数量设为 0
//                if (priceList.isEmpty()) {
//                    totalCount = 0;
//                    LogUtil.warn("获取商品规格失败 : {}", item);
//                }
////                    // 最小优惠挡位达成数量
////                    Integer min = priceList.get(0).getSuccessGear();
////                    // 最大优惠挡位达成数量
////                    Integer max = priceList.get(priceList.size() - 1).getSuccessGear();
////                    // (当前批次购买数量 % 最大挡位达成数量 > 最小挡位挡位达成数量 ?
////                    // 当前批次购买数量 % 最大挡位达成数量 % 最小挡位挡位达成 : 当前批次购买数量 % 最大挡位达成数量)
////                    int t = totalCount % max;
////                    totalCount = t > min ? t % min : t;
////                }
//                item.setRemark(String.valueOf(totalCount));
//            });
//            object.put("specList", merchantSpecs);
//        } else {
//            map.put("groupGoodsId", merchantGroupGoods.getId());
//            int totalCount = usGroupGoodsOrderService.totalCount(map);
//            merchantGroupGoods.setRemark(String.valueOf(totalCount));
//        }
//        //优惠价格档位
//        List<MerchantGroupGoodsPrice> groupGoodsPrices = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, id));
//        object.put("groupGoodsPrices", groupGoodsPrices);
//        //店铺信息
//        MerchantInfo merchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().select(MerchantInfo.STORE_AVATAR, MerchantInfo.STORE_NAME, MerchantInfo.PHONE).eq(MerchantInfo.ID, merchantGroupGoods.getMerchantId()));
//        object.put("shopInfo", merchantInfo);
//        //评价列表，两条
//        List<UsEvaluate> collect = usEvaluateService.listForUpdate(new QueryWrapper<UsEvaluate>().eq(UsEvaluate.TYPE, 4).eq(UsEvaluate.ITEM_ID, merchantGroupGoods.getId())).stream().limit(2).collect(Collectors.toList());
//        object.put("evaList", collect);
//        //拼团中的成员
//        List<Long> usGroupGoodsOrders = usGroupGoodsOrderService.thyDayUsAvatar(id, merchantGroupGoods.getBatchNum());
//        JSONArray orderArray = new JSONArray();
//        usGroupGoodsOrders.forEach(item -> {
//            UsInfo usInfo = usInfoService.getByIdForUpdate(item);
//            JSONObject orderObj = new JSONObject(true);
//            orderObj.put("avatar", usInfo.getAvatar());
//            orderObj.put("nick", usInfo.getNick());
//            orderArray.add(orderObj);
//        });
//        object.put("orderList", orderArray);
//        //最大可返现
//        BigDecimal maxNum;
//        map.clear();
//        if (merchantGroupGoods.getHasSpec() == 1) {
//            List<BigDecimal> priceList = new ArrayList<>();
//            assert merchantSpecs != null;
//            merchantSpecs.forEach(spec -> {
//                List<MerchantGroupGoodsPrice> specPrices = merchantGroupGoodsPriceService.listForUpdate(
//                        new QueryWrapper<MerchantGroupGoodsPrice>()
//                                .eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, id)
//                                .eq(MerchantGroupGoodsPrice.SPEC_ID, spec.getId()));
//                //找出当前规格最优惠的价格
//                BigDecimal min = specPrices.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//                //当前规格差价存到列表中，等规格遍历完后遍历该列表获取最大差价
//                priceList.add(spec.getOriginPrice().subtract(min));
//            });
//            maxNum = priceList.stream().max(Comparator.comparing(BigDecimal::doubleValue)).get();
//        } else {
//            map.put("groupGoodsId", merchantGroupGoods.getId());
//            BigDecimal min = groupGoodsPrices.stream().min(Comparator.comparing(MerchantGroupGoodsPrice::getDiscountPrice)).get().getDiscountPrice();
//            maxNum = merchantGroupGoods.getOriginalPrice().subtract(min);
//            //无规格当前达标人数
//            object.put("current", usGroupGoodsOrderService.totalCount(map));
//        }
//        object.put("maxNumber", maxNum);
//        return ReturnBody.success(object);
//    }

//    @ApiOperation("拼单商品提交订单")
//    @PostMapping("groupSubOrder")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "groupGoodsId", value = "团购商品id", required = true),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "count", value = "数量/数量", required = true),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "province", value = "省", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "city", value = "市", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "area", value = "区", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "address", value = "详细地址", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "name", value = "收货人", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "phone", value = "收货电话", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "0自提 1快递 2均支持 3配送", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "specId", value = "规格id", required = false),
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "payType", value = "支付类型1余额支付 2微信支付", required = false),
//    })
//    @ParameterVerify(notNull = {"groupGoodsId", "count"})
//    @RequestLimiter(ipLimit = true, msg = "当前活动过于火爆，请稍后再试")
//    public String openOrJoinGroup(Long groupGoodsId, Integer count, Long specId, String province, String city,
//                                  String area, String address, String name, String phone, Integer type, String lng, String lat, Integer payType) {
//        Long usId = (Long) request.getAttribute("usId");
//        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(groupGoodsId);
//        if (!CommUtil.checkNull(merchantGroupGoods) || merchantGroupGoods.getStatus() != 0) {
//            return ReturnBody.error("当前团购商品不存在或已下架");
//        }
//        //查询用户短时间内是否已提交过订单
//        int orderCount = usGroupGoodsOrderService.queryShortOrder(usId);
//        if (orderCount != 0) {
//            return ReturnBody.error("您刚刚已提交过订单，为保证正常交易，请等待半分钟后再提交");
//        }
//        // 判断商品是否支持用户选择得 收货方式
//        Integer method = merchantGroupGoods.getType();
//        if (!method.equals(2) && !method.toString().contains(type.toString())) {
//            String errMessage;
//            switch (type) {
//                case 0:
//                    errMessage = "该商品不支持自提";
//                    break;
//                case 1:
//                    errMessage = "该商品不支持快递";
//                    break;
//                case 3:
//                    errMessage = "该商品不支持配送";
//                    break;
//                default:
//                    errMessage = null;
//                    break;
//            }
//
//            if (errMessage == null) {
//                return ReturnBody.error();
//            } else {
//                return ReturnBody.error(errMessage);
//            }
//        }
//
//        //是否在规定时间内开团
//        LocalDateTime now = LocalDateTime.now(DateFormatTemplate.ZONE_SHANGHAI);
//        LocalDateTime start = DateFormatTemplate.paresDate(merchantGroupGoods.getStartTime());
//        LocalDateTime end = DateFormatTemplate.paresDate(merchantGroupGoods.getEndTime());
//        if (now.isBefore(start) || now.isAfter(end)) {
//            return ReturnBody.error("当前商品不在指定开团时间段");
//        }
//
//
//        //商品快照
//        JSONObject snapshot = new JSONObject();
//        snapshot.put("img", merchantGroupGoods.getImg());
//        snapshot.put("title", merchantGroupGoods.getTitle());
//        snapshot.put("type", merchantGroupGoods.getType());
//        snapshot.put("content", merchantGroupGoods.getContent());
//        snapshot.put("unit", merchantGroupGoods.getUnit());
//        snapshot.put("avatar", merchantGroupGoods.getAvatar());
//        //创建订单,二维码支付后生成
//        String orderNo = UUIDUtil.getTimeId() + UUIDUtil.getLetter();
//        UsGroupGoodsOrder usGroupGoodsOrder = new UsGroupGoodsOrder().setStatus(0).setUsId(usId).setGroupGoodsId(groupGoodsId).setOrderNo(orderNo).setType(type)
//                .setMerchantId(merchantGroupGoods.getMerchantId()).setCount(count);
//
//        //检查库存
//        SkdGoodsSpec skdGoodsSpec = null;
//        Map<String, Object> map = new HashMap<>();
//        map.put("batch", merchantGroupGoods.getBatchNum());
//        if (CommUtil.checkNull(specId)) {
//            skdGoodsSpec = merchantSpecService.getByIdForUpdate(specId);
//            // 检查是否存在此规格商品
//            if (!CommUtil.checkNull(skdGoodsSpec) || !skdGoodsSpec.getGoodsId().equals(merchantGroupGoods.getId())) {
//                return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//            }
//            usGroupGoodsOrder.setSpecId(specId);
//            if (skdGoodsSpec.getInventory() != -1) {
//                //检查规格库存
//                if (skdGoodsSpec.getInventory() < count) {
//                    return ReturnBody.error("该规格库存不足");
//                }
//                //库存扣减
//                skdGoodsSpec.setInventory(skdGoodsSpec.getInventory() - count);
//                snapshot.put("inventory", skdGoodsSpec.getInventory() - count);
//            }
//
//            //订单原价
//            usGroupGoodsOrder.setTotalPrice(skdGoodsSpec.getOriginPrice().multiply(new BigDecimal(count)));
//            usGroupGoodsOrder.setRealPrice(skdGoodsSpec.getOriginPrice().multiply(new BigDecimal(count)));
//
//            //判断今天总数量/重量是否达到优惠档次
//            map.put("specId", skdGoodsSpec.getId());
//            int totalCount = usGroupGoodsOrderService.totalCount(map);
//            totalCount += count;
//            List<MerchantGroupGoodsPrice> priceList = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>()
//                    .eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, groupGoodsId).eq(MerchantGroupGoodsPrice.SPEC_ID, specId))
//                    .stream().sorted(Comparator.comparing(MerchantGroupGoodsPrice::getSuccessGear).reversed()).collect(Collectors.toList());
//            int finalTotalCount = totalCount;
//
//            final boolean[] hasReach = {false};
//            priceList.forEach(item -> {
//                if (hasReach[0]) {
//                    return;
//                }
//                if (finalTotalCount >= item.getSuccessGear()) {
//                    //达到优惠档位，设置订单实际需要支付价格(优惠价，后续如果有更优惠价格则补差价)
//                    usGroupGoodsOrder.setRealPrice(item.getDiscountPrice().multiply(new BigDecimal(count)));
//                    hasReach[0] = true;
//                }
//            });
//            usGroupGoodsOrder.setSpecId(skdGoodsSpec.getId());
//            //封装快照规格参数
//            snapshot.put("specName", skdGoodsSpec.getDescription());
//            snapshot.put("originPrice", skdGoodsSpec.getOriginPrice());
//            snapshot.put("discountPrice", skdGoodsSpec.getPrice());
//        } else {
//            //无规格
//            if (merchantGroupGoods.getInventory() != -1) {
//                //检查商品库存
//                if (merchantGroupGoods.getInventory() < count) {
//                    return ReturnBody.error("商品库存不足");
//                }
//                merchantGroupGoods.setInventory(merchantGroupGoods.getInventory() - count);
//            }
//            map.put("groupGoodsId", merchantGroupGoods.getId());
//            int totalCount = usGroupGoodsOrderService.totalCount(map);
//            totalCount += count;
//            usGroupGoodsOrder.setTotalPrice(merchantGroupGoods.getOriginalPrice().multiply(new BigDecimal(count)));
//            usGroupGoodsOrder.setRealPrice(merchantGroupGoods.getOriginalPrice().multiply(new BigDecimal(count)));
//            List<MerchantGroupGoodsPrice> priceList = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, groupGoodsId))
//                    .stream().sorted(Comparator.comparing(MerchantGroupGoodsPrice::getSuccessGear).reversed()).collect(Collectors.toList());
//            int finalTotalCount = totalCount;
//            final boolean[] hasReach = {false};
//            priceList.forEach(item -> {
//                if (hasReach[0]) {
//                    return;
//                }
//                if (finalTotalCount >= item.getSuccessGear()) {
//                    //达到优惠档位，设置订单实际需要支付价格(优惠价，后续如果有更优惠价格则补差价)
//                    usGroupGoodsOrder.setRealPrice(item.getDiscountPrice().multiply(new BigDecimal(count)));
//                    hasReach[0] = true;
//                }
//            });
//        }
//        usGroupGoodsOrder.setSnapshot(snapshot.toJSONString());
//
//        //收货类型处理
//        if (type == 1) {
//            if (!CommUtil.checkNull(address, phone, name, province, city, area)) {
//                return ReturnBody.error("请完整填写地址信息");
//            }
//            //处理地址
//            QueryWrapper<UsAddress> eq = new QueryWrapper<UsAddress>().eq(UsAddress.PROVINCE, province).eq(UsAddress.CITY, city).eq(UsAddress.AREA, area).eq(UsAddress.ADDRESS, address).eq(UsAddress.NAME, name)
//                    .eq(UsAddress.PHONE, phone).eq(UsAddress.US_ID, usId);
//            UsAddress usAddress = usAddressService.getOneForUpdate(eq);
//            if (!CommUtil.checkNull(usAddress)) {
//                usAddress = new UsAddress();
//                usAddress.setAddress(address).setPhone(phone).setProvince(province).setCity(city).setArea(area).setUsId(usId).setName(name);
//                if (!usAddressService.save(usAddress)) {
//                    return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
//                }
//            }
//            usGroupGoodsOrder.setAddressId(usAddress.getId());
//            if (merchantGroupGoods.getHasFreeShipp() == -1) {
//                //计算运费
//                MerchantFreightTemplate merchantFreightTemplate = merchantFreightTemplateService.getByIdForUpdate(merchantGroupGoods.getFreightId());
//                //设置默认运费
//                usGroupGoodsOrder.setFreightPrice(merchantFreightTemplate.getDefaultPrice());
//                String[] ids = merchantFreightTemplate.getLocationIds().split(",");
//                //判断是否在指定区域里面
//                SysLocation sysLocation = sysLocationService.getOneForUpdate(new QueryWrapper<SysLocation>().eq(SysLocation.NAME, usAddress.getArea()));
//                if (!CommUtil.checkNull(sysLocation)) {
//                    return ReturnBody.error("收货地址错误！");
//                }
//                for (String id : ids) {
//                    //如果有指定区域的运费的话，那么就替换为指定区域运费
//                    long locationId = Long.parseLong(id);
//                    if (locationId == sysLocation.getId()) {
//                        usGroupGoodsOrder.setFreightPrice(merchantFreightTemplate.getAreaPrice());
//                    }
//                }
//                //总价添加运费
//                usGroupGoodsOrder.setTotalPrice(usGroupGoodsOrder.getTotalPrice().add(usGroupGoodsOrder.getFreightPrice()));
//                usGroupGoodsOrder.setRealPrice(usGroupGoodsOrder.getRealPrice().add(usGroupGoodsOrder.getFreightPrice()));
//            }
//            // 配送业务
//        } else if (type == 3) {
//            if (!CommUtil.checkNull(address, phone, name, province, city, area)) {
//                return ReturnBody.error("请完整填写地址信息");
//            }
//            if (!CommUtil.checkNull(lng, lat)) {
//                return ReturnBody.error("您的订单需要配送,请先定位再购买");
//            }
//            SysLocation location = sysLocationService.getLocationInfo(lng, lat);
//            if (!CommUtil.checkNull(location)) {
//                return ReturnBody.error("获取地区信息错误,您的订单需要配送,请尝试重新定位");
//            }
//            // 用户是否在支持配送的区域
//            boolean result = Arrays.stream(merchantGroupGoods.getLocationIds().split(",")).anyMatch(
//                    id -> Integer.valueOf(id).equals(location.getId())
//            );
//            if (!result) {
//                return ReturnBody.error("抱歉,您当前的位置,不支持配送");
//            }
//            //处理地址
//            QueryWrapper<UsAddress> eq = new QueryWrapper<UsAddress>().eq(UsAddress.PROVINCE, province).eq(UsAddress.CITY, city).eq(UsAddress.AREA, area).eq(UsAddress.ADDRESS, address).eq(UsAddress.NAME, name)
//                    .eq(UsAddress.PHONE, phone).eq(UsAddress.US_ID, usId);
//            UsAddress usAddress = usAddressService.getOneForUpdate(eq);
//            if (!CommUtil.checkNull(usAddress)) {
//                usAddress = new UsAddress();
//                usAddress.setAddress(address).setPhone(phone).setProvince(province).setCity(city).setArea(area).setUsId(usId).setName(name);
//                if (!usAddressService.save(usAddress)) {
//                    return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
//                }
//            }
//            usGroupGoodsOrder.setAddressId(usAddress.getId());
//        }
//        merchantGroupGoods.setSale(merchantGroupGoods.getSale() + count);
//        usGroupGoodsOrder.setBatch(merchantGroupGoods.getBatchNum()).setPayType(payType);
//        usGroupGoodsOrderService.openOrJoinGroup(merchantGroupGoods, skdGoodsSpec, usGroupGoodsOrder);
//        return ReturnBody.success(usGroupGoodsOrder.getOrderNo());
//    }

    @ApiOperation("确认订单")
    @PostMapping("confirm")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "运费模板id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String confirm(Long id) {
        MerchantFreightTemplate merchantFreightTemplate = merchantFreightTemplateService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantFreightTemplate)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        FreightTemplate freightTemplate = new FreightTemplate();
        List<String> areaList = new ArrayList<>();
        String[] split = merchantFreightTemplate.getLocationIds().split(",");
        for (String ids : split) {
            SysLocation sysLocation = sysLocationService.getByIdForUpdate(Integer.parseInt(ids));
            areaList.add(sysLocation.getName());
        }
        freightTemplate.setAreaPrice(merchantFreightTemplate.getAreaPrice());
        freightTemplate.setDefaultPrice(merchantFreightTemplate.getDefaultPrice());
        freightTemplate.setAreaList(areaList);
        return ReturnBody.success(freightTemplate);
    }


    @ApiOperation("订单余额支付")
    @PostMapping("balancePay")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单编号", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String balancePay(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGroupGoodsOrder) || !usGroupGoodsOrder.getUsId().equals(usId) || usGroupGoodsOrder.getStatus() != 0) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }

        if (usGroupGoodsOrder.getType() == 1 || usGroupGoodsOrder.getType() == 3) {
            usGroupGoodsOrder.setStatus(1);
        } else {
            usGroupGoodsOrder.setStatus(3);
        }
        usGroupGoodsOrder.setPayType(1);
        usGroupGoodsOrder.setPayTime(new Date());
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        BigDecimal payAmount;
        if (CommUtil.checkNull(usGroupGoodsOrder.getFreightPrice())) {
            payAmount = usGroupGoodsOrder.getRealPrice().add(usGroupGoodsOrder.getFreightPrice());
        } else {
            payAmount = usGroupGoodsOrder.getRealPrice();
        }
        if (usInfo.getBalance().compareTo(payAmount) < 0) {
            return ReturnBody.error("您的余额不足");
        }

        usGroupGoodsOrderService.balancePay(usGroupGoodsOrder, payAmount, usInfo);
        return ReturnBody.success();
    }

    @ApiOperation("订单列表")
    @PostMapping(value = "orderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String orderList(PageInfo pageInfo, Integer status) {
        Long usId = (Long) request.getAttribute("usId");
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsGroupGoodsOrder> pageResult = new PageUtil<UsGroupGoodsOrder>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsGroupGoodsOrder.STATUS, status);
            }
            queryWrapper.eq(UsGroupGoodsOrder.US_ID, usId);
            queryWrapper.select(UsGroupGoodsOrder.SNAPSHOT, UsGroupGoodsOrder.ORDER_NO, UsGroupGoodsOrder.QR_CODE,
                    UsGroupGoodsOrder.STATUS, UsGroupGoodsOrder.TOTAL_PRICE, UsGroupGoodsOrder.REAL_PRICE,
                    UsGroupGoodsOrder.COUNT, UsGroupGoodsOrder.TYPE, UsGroupGoodsOrder.FREIGHT_PRICE, UsGroupGoodsOrder.GROUP_GOODS_ID, UsGroupGoodsOrder.AFTER_SALE_STATUS);
            usGroupGoodsOrderService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("订单详情")
    @PostMapping("orderDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "orderNum", value = "订单号", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String orderDetail(String orderNum) {
        JSONObject object = new JSONObject(true);
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        object.put("order", usGroupGoodsOrder);
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usGroupGoodsOrder.getMerchantId());
        object.put("storeAvatar", merchantInfo.getStoreAvatar());
        object.put("storeName", merchantInfo.getStoreName());
        object.put("phone", merchantInfo.getPhone());
        //自提单显示自提地址
        if (usGroupGoodsOrder.getType() == 0) {
            MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(usGroupGoodsOrder.getGroupGoodsId());
            object.put("address", merchantGroupGoods.getSelfMentionAddress());
            object.put("lat", merchantGroupGoods.getLatLng().split(",")[0]);
            object.put("lng", merchantGroupGoods.getLatLng().split(",")[1]);
        }


        return ReturnBody.success(object);
    }

    @ApiOperation("取消订单")
    @PostMapping("cancelOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "orderNum", value = "订单号", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String cancelOrder(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGroupGoodsOrder)) {
            return ReturnBody.error("订单不存在");
        }
        if (!usGroupGoodsOrder.getUsId().equals(usId)) {
            return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
        }
        if (usGroupGoodsOrder.getStatus() != 0) {
            return ReturnBody.error("订单状态错误");
        }
        usGroupGoodsOrder.setStatus(-1);
        if (!usGroupGoodsOrderService.updateById(usGroupGoodsOrder)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("确认收货")
    @PostMapping("theGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "id", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String theGoods(String orderNum) {
        Long usId = (Long) request.getAttribute("usId");
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGroupGoodsOrder) || !usGroupGoodsOrder.getUsId().equals(usId)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usGroupGoodsOrder.getType() == 0) {
            return ReturnBody.error("自提订单需要商家扫码核销");
        }
        if (usGroupGoodsOrder.getStatus() != 2) {
            return ReturnBody.error("订单状态错误");
        }
        usGroupGoodsOrder.setStatus(5);
        usGroupGoodsOrder.setDeliveryTime(new Date());
        usGroupGoodsOrderService.theGoods(usGroupGoodsOrder);
        return ReturnBody.success();
    }
}
